package com.jnc.pay.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.jnc.pay.constant.BizConstant;
import com.jnc.pay.core.model.BaseReq;
import com.jnc.pay.core.model.BaseResp;
import com.jnc.pay.util.convert.JsonUtil;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HttpUtil {
    public static final HttpUtil instance = new HttpUtil();

    @Value("${secret.priKey}")
    private String priKey;

	public void resp(BaseReq req, BaseResp resp) {
		HttpServerRequest request = (HttpServerRequest) req.getParams(BizConstant.REQ_KEY);
		HttpServerResponse response = request.response();
		response.setStatusCode(200);

        String json = JsonUtil.bean2Json(resp);
        log.info("before encrypt resp: {}", json);
        // 加密
        try{
            json = encrypt(json);
            json = json;
        }catch (Exception e){
            log.error("resp encrypt exception, resp: {}, failure.exception: {}", resp, ExceptionUtils.getStackTrace(e));
        }
        log.info("after encrypt resp: {}", json);
        response.end(json);
        response.close();
	}

    private String encrypt(String json){
        RSA rsa = new RSA(priKey, null);
        byte[] encrypt = rsa.encrypt(StrUtil.bytes(json, CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);
        return Base64.encode(encrypt);
    }

}
